package com.code.demo.update;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.support.annotation.RequiresApi;

import com.code.demo.bean.Update;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class UpdateManager {

    private static UpdateManager updateManager;
    private Context context;

    // 下载线程
    private Thread downLoadThread;
    // 下载包保存路径
    private String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/demo/update/";
    // apk保存完整路径
    private String apkFilePath = "";
    // 临时下载文件路径
    private String tmpFilePath = "";

    public Update updateInfo;

    public UpdateManager(Context context) {
        this.context = context;
    }

    public static UpdateManager getUpdateManager(Context context) {
        if (updateManager == null) {
            updateManager = new UpdateManager(context);
        }
        return updateManager;
    }

    //判断sp中版本是否比当前app的新，并且检查对应的apk是否存在
    public boolean checkApkFile(Update update) {
        File file = new File(savePath);
        if (!file.exists()) {
            file.mkdirs();
            return false;
        }

        updateInfo = update;

        //检查文件是否存在
        String apkName = "qibu-" + updateInfo.getVersionName() + ".apk";
        apkFilePath = savePath + apkName;
        File ApkFile = new File(apkFilePath);
        // 是否已下载更新文件
        if (ApkFile.exists()) {
            return true;
        } else {
            downloadApk();
            return false;
        }
    }

    //子线程下载apk
    public Runnable mdownApkRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                //此处等待30s是为了避免和加载首页的数据抢占网络资源
                Thread.sleep(1000 * 3);

                String apkName = "qibu-" + updateInfo.getVersionName() + ".apk";
                String tmpApk = "qibu-" + updateInfo.getVersionName() + ".tmp";

                // 判断是否挂载了SD卡
                String storageState = Environment.getExternalStorageState();
                if (storageState.equals(Environment.MEDIA_MOUNTED)) {
                    File file = new File(savePath);
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    apkFilePath = savePath + apkName;
                    tmpFilePath = savePath + tmpApk;
                }

                // 没有挂载SD卡，无法下载文件
                if (apkFilePath == null || apkFilePath == "") {
                    return;
                }

                File ApkFile = new File(apkFilePath);
                // 是否已下载更新文件
                if (ApkFile.exists()) {
                    return;
                }

                // 输出临时下载文件
                File tmpFile = new File(tmpFilePath);
                FileOutputStream fos = new FileOutputStream(tmpFile);

                URL url = new URL(updateInfo.getApkUrl());
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.connect();
                InputStream is = conn.getInputStream();

                byte buf[] = new byte[2048];
                do {
                    int numread = is.read(buf);
                    if (numread <= 0) {
                        // 下载完成 - 将临时下载文件转成APK文件
                        tmpFile.renameTo(ApkFile);
                        // 通知显示红点提醒，写sp
                        break;
                    }
                    fos.write(buf, 0, numread);
                } while (true);// 点击取消就停止下载

                fos.close();
                is.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    /**
     * 下载apk
     *
     * @param //url
     */
    public void downloadApk() {
        downLoadThread = new Thread(mdownApkRunnable);
        downLoadThread.start();
    }

    /**
     * 安装apk
     *
     * @param //url
     */
    public void installApk() {
        String apkName = "qibu-" + updateInfo.getVersionName() + ".apk";
        apkName = savePath + apkName;

        File apkFile = new File(apkName);
        if (!apkFile.exists()) {
            return;
        }
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setDataAndType(Uri.parse("file://" + apkFile.toString()),
                "application/vnd.android.package-archive");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            boolean hasInstallPermission = context.getPackageManager().canRequestPackageInstalls();
            if (!hasInstallPermission) {
                startInstallPermissionSettingActivity();
                return;
            }
        }
        context.startActivity(i);
    }

    /**
     * 跳转到设置-允许安装未知来源-页面
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startInstallPermissionSettingActivity() {
        //注意这个是8.0新API
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
}